/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.control;

import it.polimi.meteocal.entity.Event;
import it.polimi.meteocal.entity.Forecast;
import it.polimi.meteocal.entity.InvitedList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author paolo
 */
@Singleton
public class OneDayService {

    private final int badMinRange = 800;
    private final int badMaxRange = 804;
    @PersistenceContext
    private EntityManager em;
    @EJB
    private MessageManager mm;

    /**
     * scheduled method execute once a day at 0:22 that control all the outdoor
     * event of one day that will take place after one day checking if there are
     * bad condition and sending a message to the author and to the
     * partecipating user
     */
    @Schedule(dayOfWeek = "*", hour = "0", minute = "22")
    public void oneDayCheck() {
        System.out.println("**************ONE DAY CHECK*********");
        TypedQuery<Forecast> forecastQuery = em.createQuery("SELECT f FROM Forecast f WHERE f.forecastDate = :day", Forecast.class);
        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        System.out.println(cal.getTime());
        forecastQuery.setParameter("day", cal);
        for (Forecast f : forecastQuery.getResultList()) {
            System.out.println("***forecast to check: " + f.getCity() + " " + f.getForecastDate().getTime());
            if (badMinRange <= f.getForecast() && f.getForecast() <= badMaxRange) {
                System.out.println("GOOD WEATHER");
            } else {
                System.out.println("BAD WEATHER");
                for (Event e : f.getEventCollection()) {
                    System.out.println("******event related to to the forecast: " + e.getName() + " " + e.getCity() + " " + e.getStartDate().getTime());
                    ArrayList<String> invitedUser = new ArrayList<>();
                    for (InvitedList i : e.getInvitedListCollection()) {
                        if (i.getPartecipation() != null) {
                            if (i.getPartecipation()) {
                                invitedUser.add(i.getUser().getEmail());
                            }
                        }
                    }
                    invitedUser.add(e.getAuthor().getEmail());
                    mm.addInvitedMessage(e, invitedUser, mm.createMessage(e, 3));
                }
            }
        }
    }
}
